iT邦幫忙

2024 iThome 鐵人賽

DAY 8
0

前幾天分別講解子查詢、集合運算的使用, 今日會更進階的搭配邏輯運算子進行資料的查詢。

邏輯運算子

常用的邏輯運算子

運算子 Function
AND A且B (兩條件成立 or 兩集合存在
OR A或者B (兩條件擇一成立 or 兩集合擇一存在)
ESIXTS 存在 (常用於主查詢是否含有子查詢的結果)
IN 用於值存在於集合
LIKE 用於比對搜尋 (通常搭配萬用字元or跳脫字元寫比對公式)
NOT 非 (可搭配 AND / EXISTS 使用)

Example使用的table

with Travel as (
    select 'Amy' name, 'Japan' country
    union all
    select 'Oleve' name, 'Denmark' country
    union all
    select 'Jake' name, 'France' country
    union all
    select 'Luisa' name, 'Greece' country
    union all
    select 'Freddy%' name, 'Japan' country
    union all
    select 'Freddy%' name, 'Greece' country  -- 新增一項
), Student as (
    select 'Amy' name, 123456 ID
    union all
    select 'Oleve' name, 567899 ID
    union all
    select 'Jake' name, 586966 ID
)

EXISTS說明

  • and exists: 查詢結果與取交集相同
select name from Travel t
where 1=1
and exists (
  select t2.name from Student t2
  where t.name = t2.name
)
;
-- output
Amy
Oleve
Jake
  • and not exists: 與取差集邏輯相同, 但差別在於不移除重複項目
select name from Travel t
where 1=1
and not exists (
  select t2.name from Student t2
  where t.name = t2.name
)
;
-- output
Luisa
Freddy%
Freddy%  -- 出現第二次

IN 跟 LIKE 的差異

曾經被問過 in 跟 like 差別在哪裡, 因此分別舉例兩者用法, 希望能幫助讀者理解,
in 用於比對元素是否存在於子查詢結果中, 而like用於比對字串中是否存有特定字元

  • in: 將主查詢結果, 拿來比對是否存在子查詢, 存在才輸出結果
select name from Travel t
where 1=1
and name in (
  select t2.name from Student t2
)
;
-- output
Amy
Oleve
Jake
  • like: 比對字串中是否符合字母L, 可以搭配upper進行查詢, 其中比對的表達式%代表任一字元, _代表一個字元, 若想比對%_等保留字元,則須要搭配escape '\'做比對。
select name from Travel t
where 1=1
and name like '%L%' --比對字串中是否符合字母L
;
-- output
Luisa

select name from Travel t
where 1=1
and upper(name) like '%L%'  --比對字串中是否符合`大小寫`字母L
;
-- output
Oleve
Luisa

select name from Travel t
where 1=1
and name like '__e%'  --比對字串中是否符合第三個字元是`e`
;
-- output
Oleve
Freddy%
Freddy%

select distinct name from Travel t
where 1=1
and name like '%\%%' escape '\'  --比對字串中是否符合存在字元是`%`
;
-- output
Freddy%

上一篇
Day 7 基礎-集合運算
下一篇
Day 9 基礎-把好朋友JOIN在一起
系列文
不居功的系統隱士 - 30天由淺入深學SQL14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言